<template>
	<view class="verifyMnemonic">
		<HeaderBar title="验证助记词" showBack fixed />
		<view class="contentBox">
			<view class="mnemoic_title">
				请根据您备份的助记词，按顺序选择填充
			</view>
			<view class="mnemoic_content">
				<view class="mnemoic" @tap="look">
					<view class="items" v-for="(item, index) in selectedMnemoic" :key="index"
						@tap="removeMnemoic(index)">
						<view class="delete">
							<image src="../../static/images/login/delete.png" mode="widthFix" class="icon"></image>
						</view>
						<text>{{item.word}}</text>
					</view>
				</view>
			</view>

			<view class="mnemoic_content_select">
				<view class="mnemoic">
					<view class="items" v-for="(item, index) in shuffledMnemoic" :key="index"
						@tap="addMnemoic(item, index)">
						<text v-if="!selectedMnemoic.some(selected => selected.index === index)">{{item}}</text>
					</view>
				</view>
			</view>

			<view class="btn">
				<view class="" :data-mnemoic="mnemoic" :data-selectedMnemoic="selectedMnemoic" @tap="verifyMnemonic">
					确认
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				mnemoic: [], // 原始助记词数组
				config: {},
				shuffledMnemoic: [], // 打乱顺序的助记词
				selectedMnemoic: [] // 选中的助记词，包括索引和单词
			};
		},
		computed: {
			allchains() {
				return this.$store.getters.getAllchains;
			},
			tokenInfo() {
				const chainInfo = this.allchains.find((item) => item.chainId == this.config.chainId)
				const info = chainInfo.coin.find((item) => item.contract == this.$config
					.defaultAddress)
				return info
			},
		},
		onLoad(options) {
			const configStr = options.configStr || '';
			try {
				// 解码并反序列化 JSON 字符串
				const config = JSON.parse(decodeURIComponent(configStr));
				this.config = config
				this.mnemoic = this.config.mnemonics.split(',')
				this.shuffledMnemoic = this.shuffleArray([...this.mnemoic]);
			} catch (error) {
				console.error('Failed to parse config:', error);
			}
		},
		methods: {
			// 打乱数组顺序
			shuffleArray(array) {
				for (let i = array.length - 1; i > 0; i--) {
					const j = Math.floor(Math.random() * (i + 1));
					[array[i], array[j]] = [array[j], array[i]];
				}
				return array;
			},
			// 添加助记词到验证区域
			addMnemoic(item, index) {
				// 如果该助记词已经选中过，直接返回
				if (this.selectedMnemoic.some(selected => selected.index === index)) return;
				// 将单词和索引添加到选中的助记词数组中
				this.selectedMnemoic.push({
					word: item,
					index: index
				});
			},
			// 从验证区域移除助记词
			removeMnemoic(index) {
				this.selectedMnemoic.splice(index, 1);
			},
			// 验证助记词是否正确
			verifyMnemonic() {
				// 获取选中的助记词的单词部分
				// this.importWallet()
				const selectedWords = this.selectedMnemoic.map(item => item.word);
				if (JSON.stringify(selectedWords) === JSON.stringify(this.mnemoic)) {
					this.importWallet()
				} else {
					uni.showToast({
						title: '验证失败',
						icon: 'none'
					});
				}
			},
			importWallet() {
				let data = {
					address: this.config.address,
					privateKey: this.config.privateKey,
					mnemonics: this.mnemoic.join(','),
					chainType: this.config.chainType,
					chainName: this.config.chainName,
					chainId: this.config.chainId,
					name: this.config.name,
					password: this.config.password,
					passwordTilp: this.config.passwordTilp,
					importMethod: this.config.importMethod
				}
				let token = {
					address: this.config.address,
					chainType: this.config.chainType,
					chainName: this.config.chainName,
					chainId: this.config.chainId,
					tokenaddress: this.$config.defaultAddress,
					tokenname: this.tokenInfo.name,
					tokenimg: "",
					tokennum: "0",
					tokendemail: this.tokenInfo.decimal,
					tokensymbol: this.tokenInfo.symbol,
					tokenprice: "1",
				}

				uni.$db.insert('list', 'choinList', token).then((res) => {
					uni.$db.insert('list', 'addressList', data).then((res) => {
						this.$store.commit('setAddress', data.address);
						this.$store.commit('setChainId', this.config.chainId);
						let rpclist = uni.getStorageSync('rpclist') || [];
						const foundChain = rpclist.find(chain => chain.chainId == this.config.chainId);
						this.$store.commit('setRpc', foundChain?.defultRPC);
						this.$updateWalletInfo()
						uni.switchTab({
							url: '/pages/index/index', // 这里的路径是 tabBar 页面在项目中的路径
							success() {},
							fail(err) {}
						});
					}).catch((err) => {
						return this.toast('钱包导入失败，请退出重新导入')
					});
				}).catch((err) => {
					return this.toast('钱包导入失败，请退出重新导入')
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.verifyMnemonic {
		.contentBox {
			padding: 0 40upx;

			.mnemoic_title {
				font-size: 28upx;
				color: #3E3E3E;
				font-weight: 400;
				margin: 20upx 24upx;
			}

			.mnemoic_content {
				margin-top: 30upx;
				width: 100%;
				height: 432upx;
				padding: 20upx 16upx;
				background: #F5F7F6;
				border-radius: 20upx;
				position: relative;
				box-sizing: border-box;

				.mnemoic {
					display: grid;
					grid-template-columns: repeat(3, 1fr);
					grid-template-rows: repeat(4, 1fr);
					gap: 16upx;
					height: 392upx;

					.items {
						background: #FFFFFF;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 28upx;
						color: #3D3D3D;
						font-weight: 400;
						border-radius: 20upx;
						position: relative;

						.delete {
							position: absolute;
							right: -10upx;
							top: -10upx;
							width: 38upx;
							height: 38upx;

							.icon {
								width: 38upx;
								height: 38upx;
							}
						}

						.index {
							margin-right: 10upx;
							color: #999999;
						}
					}
				}
			}

			.mnemoic_content_select {
				margin-top: 38upx;

				.mnemoic {
					display: grid;
					grid-template-columns: repeat(4, 1fr);
					grid-template-rows: repeat(3, 1fr);
					gap: 16upx;
					height: 244upx;

					.items {
						background: #FFFFFF;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 28upx;
						color: #3D3D3D;
						font-weight: 400;
						border-radius: 20upx;
						border: 1px solid #B2B2B2;

						.index {
							margin-right: 10upx;
							color: #999999;
						}
					}
				}
			}

			.btn {
				font-size: 26upx;
				color: #F6F6F6;
				line-height: 88upx;
				background: linear-gradient(180deg, #A9E993 0%, #368321 100%);
				border-radius: 10upx;
				text-align: center;
				margin-top: 100upx;
			}
		}
	}
</style>